#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'HaiFeng'
__mtime__ = '2016/8/16'
"""

import multiprocessing
from time import sleep

from py_at.Tool import printLog
from py_at.py_at_adapter_test import *
from datetime import datetime, time
import sys
import os
#---------------------------------------------------------------------
def runChildProcess():
    """处理日志事件"""
    print ('-'*20)
    printLog(u'启动CTA策略运行子进程')
    a = AdapterTest()
    a.load_strategy_json()  # 加载策略配置文件
    a.load_strategyname()  # 加载所有策略类名
    a.load_all_Instrument()  # 加载所有合约信息
    a.TradeInit()            #实盘登陆
    printLog(u'启动实盘交易账户')
    sleep(10)
    a.createlogInfo()   #启动日志记录功能
    printLog(u'循环加载策略配置')
    for k in a.CanshuDict.keys(): #加载所有策略实例
        a.initstra(k)
    printLog(u'循环启动实盘交易')
    for k in a.CanshuDict.keys(): #加载所有策略实例
        a.trading(k)
    a.autoSynchOrderThread.start()
    print('系统启动完毕！')
    while True:
        sleep(1)
#----------------------------------------------------------------------
def runParentProcess():
    """父进程运行函数"""
    printLog('启动CTA策略守护父进程')
    DAY_START = time(8, 30)  # 日盘启动和停止时间
    DAY_END = time(15, 10)
    NIGHT_START = time(20,30)
    NIGHT_END=time(2,40)
    p= None
    while True:
        currentTime = datetime.now().time()
        recording = False
        # 判断当前处于的时间段
        if ((currentTime >= DAY_START and currentTime <= DAY_END) or(currentTime >= NIGHT_START) or(currentTime <= NIGHT_END)):
            recording = True
        # 记录时间则需要启动子进程
        if recording and p is None:
            printLog(u'启动子进程')
            p = multiprocessing.Process(target=runChildProcess)
            p.start()
            p.join()
            printLog(u'子进程启动成功')
        #非记录时间退出子进程
        if not recording and p is not None:
            printLog(u'关闭子进程')
            p.terminate()
            p.join()
            p=None
            printLog('子进程关闭成功')
        sleep(5)
if __name__=='__main__':
    #runParentProcess()
    runChildProcess()